import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

// 导入组件
const Login = () => import('@/views/login/index.vue')
const Home = () => import('@/views/home/index.vue/')
const Video = () => import('@/views/video/index.vue/')
const User = () => import('@/views/user/index.vue/')
const Article = () => import('@/views/article/index.vue/')
const Question = () => import('@/views/question/index.vue/')
const UserProfile = () => import('@/views/profile/index.vue/')
const UserChat = () => import('@/views/chat/index.vue/')
const Tabbar = () => import('@/components/tabbar.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    alias: '/home',
    components: { default: Home, bottom: Tabbar }
  },
  {
    path: '/video',
    components: { default: Video, bottom: Tabbar }
  },
  {
    path: '/user',
    components: { default: User, bottom: Tabbar },
    meta: {
      needLogin: true // 需要登录才能访问
    }
  },
  {
    path: '/article/:id?',
    name: 'Article',
    component: Article
  },
  {
    path: '/question',
    components: { default: Question, bottom: Tabbar }
  },
  {
    path: '/user/profile',
    component: UserProfile,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user/chat',
    component: UserChat,
    meta: {
      needLogin: true
    }
  }
]

const router = new VueRouter({
  routes
})
// 白名单
// const writePath = ['/user', '/video', '/user/profile']
// 路透前置守卫
router.beforeEach((to, from, next) => {
  if (store.getters['user/getToken']) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 小白写法
    // if (to.path.toLowerCase().startsWith('/user')) {
    // 白名单模式
    // if (writePath.includes(to.path.toLowerCase())) {
    // 路由元模式
    if (to.meta.needLogin) {
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
})

export default router
